﻿
@{
    ViewBag.Title = "Index";
}
@section styles{
    <link href="~/lib/webuploader.css" rel="stylesheet" />
    <style>
        #actionHeader {
            overflow: hidden;
        }

        #videoActions {
            padding: 10px 0;
            float: right;
        }

        #btnUpload {
            float: left;
        }

        #uploadVideoSection .progress-bar {
            min-width: 2em;
        }
    </style>
}
<div class="jumbotron">
    <h4>视频中心</h4>
    <ul class="list-group">
        <li class="list-group-item">
            <strong>视频总数：</strong>
            <span class="badge bg-primary">
                <span>28</span>
                <span>个</span>
            </span>
        </li>
        <li class="list-group-item">
            <strong>视频总大小：</strong>
            <span class="badge">
                <span>448.15</span>
                <span>GB</span>
            </span>
        </li>

        <li class="list-group-item">
            <strong>剩余磁盘可用空间：</strong>
            <span class="badge">
                <span>4.33</span>
                <span>GB</span>
            </span>
        </li>
        <li class="list-group-item">
            <strong>客户端总数：</strong>
            <span class="badge">
                <span>238</span>
                <span>个</span>
            </span>

        </li>

    </ul>
</div>
<div>
    <div id="alertContent"></div>
    <div>

        <!-- Nav tabs -->
        <ul class="nav nav-tabs" role="tablist">
            <li role="presentation" class="active"><a href="#inUpload" aria-controls="inUpload" role="tab" data-toggle="tab">上传中</a></li>
            <li role="presentation"><a href="#uploadCompleted" aria-controls="uploadCompleted" role="tab" data-toggle="tab">已完成</a></li>
        </ul>

        <!-- Tab panes -->
        <div class="tab-content">
            <div role="tabpanel" class="tab-pane active" id="inUpload">
                @{
                    Html.RenderPartial("InUploadSection");
                }
            </div>
            <div role="tabpanel" class="tab-pane" id="uploadCompleted">
                @{
                    Html.RenderPartial("DownCompletedSection");
                }
            </div>
        </div>

    </div>
</div>
@section scripts{
    <script src="~/Scripts/jquery.signalR-2.2.2.js"></script>
    <script src="signalr/hubs"></script>
    <script src="~/lib/webuploader.js"></script>
    <script>
        var uploader;
        var uploaded
        $(function () {
            $("#uploadVideoSection tbody").empty();

            WebUploader.Uploader.register({
                "before-send-file": "beforeSendFile",//整个文件上传前
                "before-send": "beforeSend",  //每个分片上传前
                "after-send-file": "afterSendFile",  //分片上传完毕
            },
                {
                    //时间点1：所有分块进行上传之前调用此函数
                    beforeSendFile: function (file) {
                        var deferred = WebUploader.Deferred();
                        //1、计算文件的唯一标记fileMd5，用于断点续传  如果.md5File(file)方法里只写一个file参数则计算MD5值会很慢 所以加了后面的参数：10*1024*1024
                        (new WebUploader.Uploader()).md5File(file).progress(function (percentage) {
                            //$('#' + file.id).find('p.state').text('正在读取文件信息...');
                        }).then(function (val) {

                            fileMd5 = val;
                            $(GetRowDomByFileId(file.id)).find(".md5Hash").text(fileMd5);
                                //获取文件信息后进入下一步
                                deferred.resolve();
                            });

                        fileName = file.name; //为自定义参数文件名赋值
                        return deferred.promise();
                    },
                    //时间点2：如果有分块上传，则每个分块上传之前调用此函数
                    beforeSend: function (block) {
                        var deferred = WebUploader.Deferred();
                        //$.ajax({
                        //    type: "POST",
                        //    url: "${ctx}/testController/mergeOrCheckChunks.do?param=checkChunk",  //ajax验证每一个分片
                        //    data: {
                        //        fileName: fileName,
                        //        jindutiao: $("#jindutiao").val(),
                        //        fileMd5: fileMd5,  //文件唯一标记
                        //        chunk: block.chunk,  //当前分块下标
                        //        chunkSize: block.end - block.start//当前分块大小
                        //    },
                        //    cache: false,
                        //    async: false,  // 与js同步
                        //    timeout: 1000, //todo 超时的话，只能认为该分片未上传过
                        //    dataType: "json",
                        //    success: function (response) {
                        //        if (response.ifExist) {
                        //            //分块存在，跳过
                        //            deferred.reject();
                        //        } else {
                        //            //分块不存在或不完整，重新发送该分块内容
                        //            deferred.resolve();
                        //        }
                        //    }
                        //});
                        this.owner.options.formData.md5 = $(GetRowDomByFileId(block.file.id)).find(".md5Hash").text();;
                        deferred.resolve();
                        return deferred.promise();
                    },
                    //时间点3：所有分块上传成功后调用此函数
                    //afterSendFile: function () {
                    //    //如果分块上传成功，则通知后台合并分块
                    //    $.ajax({
                    //        type: "POST",
                    //        url: "${ctx}/testController/mergeOrCheckChunks.do?param=mergeChunks",  //ajax将所有片段合并成整体
                    //        data: {
                    //            fileName: fileName,
                    //            fileMd5: fileMd5,
                    //        },
                    //        success: function (data) {
                    //            count++; //每上传完成一个文件 count+1
                    //            if (count <= filesArr.length - 1) {
                    //                uploader.upload(filesArr[count].id);//上传文件列表中的下一个文件
                    //            }
                    //            //合并成功之后的操作
                    //        }
                    //    });
                    //}
                });

            var BASE_URL = "http://127.0.0.1:51945";
            uploader = WebUploader.create({
                //文件选择后自动上传
                auto: true,
                prepareNextFile: true,
                // swf文件路径
                swf: '/lib/Uploader.swf',

                // 文件接收服务端。
                server: '/Video/Upload',

                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                pick: '#btnUpload',

                // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
                resize: false,
                chunked: true,//分片传输
                chunkSize: 102400,//分片大小100k(视服务器带宽，自行定义)
                threads: 1,//最大并发量
                duplicate: true,//文件去重
                formData: {},
                // 只允许选择视频文件。
                accept: {
                    title: '视频文件',
                    extensions: 'mp4,wmv,avi',
                    mimeTypes: 'video/*'
                }
            });
            // 当有文件被添加进队列的时候
            uploader.on('fileQueued', function (file) {
                var count = $("#uploadVideoSection tbody tr").length + 1;
                var domStr = [];
                domStr.push("<tr data-fid=" + file.id + ">");
                domStr.push("<td>" + count + "</td>");
                domStr.push("<td>" + file.name + "</td>");
                domStr.push("<td class='md5Hash'>正在计算中...</td>");
                domStr.push("<td>" + file.size + "</td>");
                domStr.push('<td><div class="progress"><div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">0%</div></div></td>');
                domStr.push('<td class="action"><button data-fid=' + file.id + ' class="btn btn-danger btn-rmFile">取消</button></td>');

                domStr.push("</tr>");

                var $fileRow = $(domStr.join(""));
                $("#uploadVideoSection tbody").append($fileRow);
                //uploader.md5File(file).progress(function (percentage) {

                //    $fileRow.find(".md5Hash").text("计算中:" + percentage)
                //}).then(function (val) {
                //    $fileRow.find(".md5Hash").text(val)
                //    uploader.option('formData', {
                //        "md5": val
                //    });

                //});
            });

            uploader.on('uploadSuccess', function (file) {
                var fileId = file.id;
                $("#uploadVideoSection tbody tr").each(function (index, item) {
                    if ($(this).attr('data-fid') == fileId) {
                        //$(this).remove();
                    }

                });
            });

            uploader.on('uploadError', function (file) {
                console.log(file.name + "上传失败");
            });

            uploader.on('uploadComplete', function (file) {

            });

            uploader.on("uploadProgress", function (file, percentage) {
                //console.log("文件上传进度：" + file.fileid + ":" + percentage)
                updateProgressBar(file.id, percentage);
            });

            uploader.on("uploadAccept", function (obj, ret) {
                //0 上传成功；1：分片文件完成当前片上传成功；2：文件秒传成功；其他<0错误
                    //alert("文件上传成功");
                if (ret.Code < 0) {
                    uploader.cancelFile(obj.file);
                    $(GetRowDomByFileId(obj.file.id)).find(".action").empty().append('<button class="btn btn-warning btn-retry" data-fid="' + obj.file.id + '">重试</button>');
                    alert(ret.Message);
                } else if (ret.Code == 2) {
                    updateProgressBar(obj.file.id, 1);//更新进度条
                    //$(GetRowDomByFileId(obj.file.id)).remove();
                    uploader.cancelFile(obj.file);
                    //alert("文件秒传成功");

                }
                //文件上传成功
                if (ret.Code == 0 || ret.Code == 2) {
                    $(GetRowDomByFileId(obj.file.id)).find(".action").empty().append('<span class="label label-success">上传成功</span>');
                    var statusObj = uploader.getStats();
                    //判断文件是否上传完毕
                    console.log(uploader.getStats());
                    if (statusObj.progressNum <=1 && statusObj.queueNum <=1) {
                        $.ajax({
                            url: '@Url.Action("TotalFileUploadCompleted")',
                            type: 'POST',
                            data: [],
                            success: function () { },
                            error: function () { }
                        });
                        alert("所有文件上传成功");
                    }
                }

            });
            //取消上传
            $("#uploadVideoSection").on("click", ".btn-rmFile", function () {

                var fileId = $(this).attr("data-fid");
                var targetRmFile = uploader.getFile(fileId);
                uploader.removeFile(targetRmFile);
                var rowDom = GetRowDomByFileId(fileId);
                $(rowDom).remove();

            });

            //上传失败重试
            $("#uploadVideoSection").on("click", ".btn-retry", function () {

                var fileId = $(this).attr("data-fid");
                alert(fileId);
                var targetReFile = uploader.getFile(fileId);
                uploader.retry(targetReFile)

            });

            $("#uploadedFileList").on("click", "thead input[type='checkbox']", function () {
                if ($(this).prop("checked") == true) {
                    $("#uploadedFileList tbody .check").prop("checked", true);
                } else {
                    $("#uploadedFileList tbody .check").prop("checked",false);
                }
            });
            $("#uploadedFileList").on("change", "input[type='checkbox']", function () {
                var checkItemsCount = $("#uploadedFileList tbody input[type='checkbox']:checked").length;
                if (checkItemsCount == 0) {
                    $("#videoActions .remove").attr("disabled", "disabled");
                } else {
                    $("#videoActions .remove").removeAttr("disabled");
                }
            });

            $("#videoActions .remove").click(function () {
                var delFileDoms = $("#uploadedFileList tbody input[type='checkbox']:checked").parentsUntil("tr").parent().find(".fileName");
                var delFiles = [];
                delFileDoms.each(function () {
                    delFiles.push($(this).text());
                })

                $.ajax({
                    url: '@Url.Action("DeleteFiles")',
                    data: { fileNames: delFiles},
                    type: "POST",
                    success: function (data) {
                        if (data.Code != 0) {
                            alert(data.Message);
                        }
                        //删除成功，重新加载
                        LoadRemoteVideoList();
                    }, error: function () {
                        alert("删除失败");
                    }
                })
            })
            


            function updateProgressBar(fileId, percentage) {
                percentage = Number.parseFloat(percentage * 100).toFixed(2);
                var rowDom = GetRowDomByFileId(fileId);
                var progressDom = $(rowDom).find(".progress-bar")[0];
                $(progressDom).attr("aria-valuenow", percentage).css("width", percentage + "%").text(percentage + "%");
            }

            function GetRowDomByFileId(fileId) {
                var rowObj;
                $("#uploadVideoSection tbody tr").each(function (index, item) {
                    if ($(this).attr('data-fid') == fileId) {
                        rowObj = $(this);
                        return false;
                    }
                });
                return rowObj;
            }

            function LoadRemoteVideoList() {
                $.ajax({
                url: '@Url.Action("GetFileList")',
                type: "POST",
                 success: function (data) {
                     $("#uploadedFileList tbody").empty();
                     var domStr = [];
                     $.each(data, function (index, item) {
                         domStr.push("<tr>");
                         domStr.push('<td><input class="check" type="checkbox" /></td>');
                         domStr.push('<td>' + index + '</td>');
                         domStr.push('<td class="fileName">' + item.FileName + '</td>');
                         domStr.push('<td>' + item.FileExtension + '</td>');
                         domStr.push('<td>' + item.FileHash + '</td>');
                         domStr.push('<td>' + item.FileSize + '</td>');
                         domStr.push("</tr>");
                     });
                     $("#uploadedFileList tbody").append(domStr.join(""));
                }, error: function () {
                    alert("获取数据失败");
                }
            });
            }

            var videoHub = $.connection.videoHub;
            videoHub.client.ReloadRemoteVideoList = function () {
                LoadRemoteVideoList();
            };
            //signalr连接完成
            $.connection.hub.start().done(function () {

            });
            //加载远程视频列表
            LoadRemoteVideoList();
        });

    </script>
}